package com.xlz.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xlz.manager.DefaultDstManager;
import com.xlz.service.AppInstanceService;
import com.xlz.service.AppWorkerService;
import com.xlz.util.DateUtil;

/**
 * 发送心跳
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class HeartBeatTask extends TimerTask {

	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	
	private DefaultDstManager scheduleManager;

	private AppInstanceService appInstanceService;
	private AppWorkerService appWorkerService;
	private Timer timer;
	
	public HeartBeatTask(DefaultDstManager scheduleManager,Timer timer) {
		this.scheduleManager = scheduleManager;
		this.appInstanceService = scheduleManager.getAppInstanceService();
		this.appWorkerService = scheduleManager.getAppWorkerService();
		this.timer = timer;
	}

	@Override
	public void run() {
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		long start = System.currentTimeMillis();
		long heartBeatRate = 3000l;
		try {
			this.cancel();
			//发送应用实例的心跳，主要是检测应用实例的存活
			appInstanceService.insertOrUpdate(scheduleManager.getContext().getAppNo(), scheduleManager.getContext().getInstanceId());
			LOG.debug("当前心跳时间："+DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
			//发送心跳，主要是更新在工作中的worker
			appWorkerService.batchUpdateByWorker(scheduleManager.getWorkerPool());
			heartBeatRate = scheduleManager.loadAppConfig();
		} catch (Exception e) {
			// 发送本机心跳错误
			LOG.error("发送当前应用心跳异常，当前引用id："+scheduleManager.getContext().getInstanceId(),e);
		}
		scheduleManager.getContext().setHeartBeatRate(heartBeatRate  );
		timer.schedule(new HeartBeatTask(scheduleManager,timer),DateUtil.timeConvert( heartBeatRate) );
		long end = System.currentTimeMillis();
		long result = end-start;
		if(result > DateUtil.timeConvert( heartBeatRate) )
			LOG.error("本次发送心跳耗时："+result +"ms,请关注数据库性能和网络问题");
	}
	
}
